package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.*;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.Spu;
import com.leyou.item.pojo.SpuDetail;
import com.leyou.item.service.port.IGoodsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.leyou.common.constants.MQConstants.Exchange.ITEM_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_DOWN_KEY;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_UP_KEY;

@Service
public class GoodsService implements IGoodsService{

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    public PageResult<SpuDTO> querySpuByPage(Integer page, Integer rows, Boolean saleable, String key) {
        // 1 分页
        PageHelper.startPage(page, rows);
        // 2 过滤
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 2.1 搜索条件过滤
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("name", "%" + key + "%");
        }
        // 2.2 上下架过滤
        if(saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }
        // 2.3 默认按时间排序
        example.setOrderByClause("update_time DESC");
        // 3 查询结果
        List<Spu> list = spuMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        // 4 封装分页结果
        PageInfo<Spu> info = new PageInfo<>(list);

        // DTO转换
        List<SpuDTO> spuDTOList = BeanHelper.copyWithCollection(list, SpuDTO.class);
        // 5 处理分类名称和品牌名称
        handleCategoryAndBrandName(spuDTOList);

        return new PageResult<>(info.getTotal(), spuDTOList);
    }



    private void handleCategoryAndBrandName(List<SpuDTO> list) {
        for (SpuDTO spu : list) {
            // 查询分类
            String categoryName = categoryService.queryCategoryByIds(spu.getCategoryIds())
                    .stream()
                    .map(CategoryDTO::getName).collect(Collectors.joining("/"));
            spu.setCategoryName(categoryName);
            // 查询品牌
            BrandDTO brand = brandService.queryById(spu.getBrandId());
            spu.setBrandName(brand.getName());
        }
    }


    @Override
    @Transactional
    public void saveGoods(SpuDTO spuDTO) {

        // 从dto中取出spu信息
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        // 保存spu
        spu.setId(null);
        spu.setCreateTime(null);
        spu.setSaleable(null);
        int count = spuMapper.insertSelective(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        // 初始化SpuDetail信息
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        spuDetail.setSpuId(spu.getId());
        // 保存spu详情
        count = spuDetailMapper.insertSelective(spuDetail);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        // 准备sku数据
        List<SkuDTO> skuDTOList = spuDTO.getSkus();
        List<Sku> skuList = new ArrayList<>();
        for (SkuDTO skuDTO : skuDTOList) {
            skuDTO.setSpuId(spu.getId());
            skuList.add(BeanHelper.copyProperties(skuDTO, Sku.class));
        }
        // 保存sku
        count = skuMapper.insertList(skuList);
        if (count != skuList.size()) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

    }

    @Override
    public SpuDetailDTO querySpuDetailById(Long spuId) {
        SpuDetail spuDetail = this.spuDetailMapper.selectByPrimaryKey(spuId);
        return BeanHelper.copyProperties(spuDetail,SpuDetailDTO.class);
    }

    @Override
    public List<SkuDTO> querySkuBySpuId(Long spuId) {

        Sku record=new Sku();
        record.setSpuId(spuId);
        List<Sku> skus = this.skuMapper.select(record);
        if (CollectionUtils.isEmpty(skus)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skus,SkuDTO.class);
    }

    @Override
    @Transactional
    public void updateGoods(SpuDTO spuDTO) {

        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);

        int count = this.spuMapper.updateByPrimaryKeySelective(spu);
        if (1 != count) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
        count = this.spuDetailMapper.updateByPrimaryKeySelective(spuDetail);
        if (1 != count) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        Sku sku = new Sku();
        sku.setSpuId(spu.getId());
        int size = skuMapper.selectCount(sku);
        if (size > 0) {
            count = skuMapper.delete(sku);
            if (count != size) {
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        }
        List<SkuDTO> skuDTOS = spuDTO.getSkus();
        skuDTOS.forEach(skuDTO -> skuDTO.setSpuId(spu.getId()));
        List<Sku> skus = BeanHelper.copyWithCollection(skuDTOS, Sku.class);
        count = this.skuMapper.insertList(skus);
        if (count != skus.size()) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

    }

    @Override
    public void modifySaleable(Long spuId,Boolean saleable) {
        Spu record=new Spu();
        record.setId(spuId);
        record.setSaleable(saleable);
        this.spuMapper.updateByPrimaryKeySelective(record);

        // 发送mq消息
        String key = saleable ? ITEM_UP_KEY : ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(ITEM_EXCHANGE_NAME,key, spuId);

    }

    @Override
    public SpuDTO querySpuById(Long id) {
        return BeanHelper.copyProperties(this.spuMapper.selectByPrimaryKey(id),SpuDTO.class);
    }

    @Override
    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        List<Sku> skus = skuMapper.selectByIdList(ids);
        if (null==skus){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skus,SkuDTO.class);
    }

    @Transactional
    @Override
    public void minusStock(Map<Long, Integer> cartMap) {
        for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
            Long skuId = entry.getKey();
            Integer num = entry.getValue();
            int count = skuMapper.minusStock(skuId, num);
            if(count != 1){
                throw new RuntimeException("库存不足");
            }
        }
    }

    @Transactional
    @Override
    public void plusStock(Map<Long, Integer> cartMap) {

        for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
            Long skuId = entry.getKey();
            Integer num = entry.getValue();
            int count = skuMapper.plusStock(skuId, num);

        }

    }


}